/* eslint  react/no-string-refs: 0 */
import React, { Component } from 'react';
import { Table, Button, Icon } from '@alifd/next';
import { ApiOfControlTest } from '#/utils/coreApiDefine'
import styles from './styles/styles';

export default class ControlTest extends Component {
  static displayName = 'ControlTest';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      group: this.props.group,
      metrics: this.props.group.metrics,
      controlLoading: false,
    };
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      group: nextProps.group,
      metrics: nextProps.group.metrics
    })    
  }

  onControlTest(metricCode) {
    this.setState({
      controlLoading: true
    })
    ApiOfControlTest(this.props.deviceCode, metricCode).then(response => {
      const metrics = this.state.metrics;
      metrics.find(it => it.code == metricCode).result = !!response.data;
      this.setState({
        metrics,
        controlLoading: false
      })
    }).catch(error => {
      const metrics = this.state.metrics;
      metrics.find(it => it.code == metricCode).result = false;
      this.setState({
        controlLoading: false
      })
    })
  }

  renderControlResult(value, index, item) {
    let ret = <span></span>

    if(item.result === true) {
      ret =  <Icon type="smile" />
    } else if(item.result === false) {
      ret =  <Icon type="cry" />
    }
    return (
        ret
    );
  }

  render() {
    const renderControlOper = (value, index, item) => {
      return (
        <div>
          <Button onClick={this.onControlTest.bind(this,item.code)} type="primary" aria-label="prompt button" warning size="small">测试</Button>
        </div>
      );
    }

    return (
      <div style={styles.infoColumn}>
        <h5 style={styles.infoColumnTitle}>控制指标</h5>
        <Table dataSource={this.state.metrics} loading={this.state.controlLoading}>
          <Table.Column title="指令" dataIndex="command"/>
          <Table.Column title="名称" dataIndex="name" />
          <Table.Column title="标识符" dataIndex="variable"/>
          <Table.Column
            width={80}
            title="测试"
            cell={renderControlOper}
          />
          <Table.Column title="测试结果" cell={this.renderControlResult}/>
        </Table>
      </div>
    );
  }
}
